#!/usr/bin/python
# -*- coding: utf-8 -*-
# Description: util tools
# Create at 2008-11-23 下午11:46:39
# Author: MK2[fengmk2@gmail.com]
"""docstrings
"""

import re

IE_USER_AGENT_RE = re.compile(r"""
    (?P<base>[a-z]*/[\d\.]*)    #base
    \s*
    \(compatible;\s
    (?P<browser>MSIE\s[\d\.]*);\s
    (?P<os>[^;)]*)[^)]*
    \)
    \s*
""", re.IGNORECASE | re.VERBOSE)

FIREFOX_USER_AGENT_RE = re.compile(r"""
    (?P<base>[a-z]*/[\d\.]*)    #base
    \s*
    \([^;]*;\s
    [^;]*;\s
    (?P<os>[^;)]*)[^)]*
    \)
    \s*
    .*?
    (?P<browser>Firefox[^\s]*)
""", re.IGNORECASE | re.VERBOSE)

SAFARI_USER_AGENT_RE = re.compile(r"""
    (?P<base>[a-z]*/[\d\.]*)    #base
    \s*
    \([^;]*;\s
    [^;]*;\s
    (?P<os>[^;)]*)[^)]*
    \)
    \s*
    .*?
    Version/(?P<version>[^\s]*)
    .*?
    (?P<browser>Safari[^\s]*)
""", re.IGNORECASE | re.VERBOSE)

CHROME_USER_AGENT_RE = re.compile(r"""
    (?P<base>[a-z]*/[\d\.]*)    #base
    \s*
    \([^;]*;\s
    [^;]*;\s
    (?P<os>[^;)]*)[^)]*
    \)
    \s*
    .*?
    (?P<browser>Chrome[^\s]*)
""", re.IGNORECASE | re.VERBOSE)

def analysis_user_agent(user_agent):
    """Analysis the User-Agent string. also see: http://www.useragentstring.com/
    
    return format:
    {'os': osname,
    'browser': browsername and version,
    'base': the browser base on what,
    }
    """
    m = IE_USER_AGENT_RE.search(user_agent)
    if not m:
        m = FIREFOX_USER_AGENT_RE.search(user_agent)
        if not m:
            m = SAFARI_USER_AGENT_RE.search(user_agent)
            if m:
                r = m.groupdict()
                r['browser'] = 'Safari/' + r['version']
                r.pop('version')
                return r
            else:
                m = CHROME_USER_AGENT_RE.search(user_agent)
    if m:
        return m.groupdict()
    return {}

_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz_+=@$'

def int_to_s(v, radix=len(_CHARS)):
    r = []
    while True:
        m = v % radix
        r.insert(0, _CHARS[m])
        v = v / radix
        if v < 36:
            if v > 0:
                r.insert(0, _CHARS[v])
            break
    return ''.join(r)

if __name__ == '__main__':
    print len(_CHARS)
    for i in range(len(_CHARS) + 1):
        print int_to_s(i)
    s = int_to_s(370, 36)
    print int(s, 36), s